package com.example.app.controller;

import com.example.app.entity.Exercise;
import com.example.app.service.DeepSeekService;
import com.example.app.service.ExerciseService;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/api/exercises")
@RequiredArgsConstructor
public class ExerciseController {

    private final ExerciseService exerciseService;
    private final DeepSeekService deepSeekService;
    private final ObjectMapper objectMapper = new ObjectMapper();
    // 获取用户所有锻炼记录
    @GetMapping("/user/{userId}")
    public List<Exercise> getExercisesByUserId(@PathVariable Long userId) {
        return exerciseService.getExercisesByUserId(userId);
    }
    @GetMapping("/user/{userId}/{date}")
    public List<Exercise> getExercisesByUserIdAndDate(
            @PathVariable Long userId,
            @PathVariable @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date) {
        return exerciseService.getExercisesByUserIdAndDate(userId,date);
    }

    // 获取用户在某天的锻炼记录
    @PostMapping("/generate")
    public List<Exercise> generateExercise(@RequestBody Map<String, String> request) throws Exception {
        Long userId = Long.parseLong(request.get("userId"));
        String idea = request.get("idea");

        String sb = "请根据健康信息为以下锻炼想法生成锻炼计划(至少列出7天)并转换为标准结构化 JSON 格式（只需输出json即可），字段包括：context（项目名字+活动量，例如：慢跑30分钟）、time（时分秒，24小时制）、date（格式为YYYY-MM-DD）、startDate（格式为YYYY-MM-DD）、endDate（格式为YYYY-MM-DD）。\n" +
                "用户想法：" + idea;
        String fullPrompt = deepSeekService.buildExercisePrompt(userId, sb);
        String jsonAnswer = deepSeekService.answerQuestion(fullPrompt, false).block();

        Pattern pattern = Pattern.compile("\\[.*?\\]", Pattern.DOTALL);
        Matcher matcher = pattern.matcher(jsonAnswer);
        if (matcher.find()) {
            jsonAnswer = matcher.group(); // 提取中括号及其内容
        } else {
            throw new IllegalArgumentException("未能从返回内容中提取有效的 JSON 数组");
        }
        System.out.println(jsonAnswer);

        // 反序列化为 List<Map<String, String>>
        List<Map<String, String>> parsedList = objectMapper.readValue(jsonAnswer, List.class);
        List<Exercise> exercises = new java.util.ArrayList<>();
        System.out.println();
        for (Map<String, String> parsed : parsedList) {
            Exercise exercise = new Exercise();
            System.out.println(parsed.get("context"));
            exercise.setContext(parsed.get("context"));
            exercise.setTime(LocalTime.parse(parsed.get("time")));
            exercise.setDate(LocalDate.parse(parsed.get("date")));
            exercise.setStartDate(LocalDate.parse(parsed.get("startDate")));
            exercise.setEndDate(LocalDate.parse(parsed.get("endDate")));
            exercise.setUserId(userId); // 如果 Exercise 中有 userId 字段，别忘了设置
            exercises.add(exerciseService.saveExercise(exercise));
        }

        return exercises;
    }
    @DeleteMapping("/user/{userId}")
    public void deleteExercisesByUserId(@PathVariable Long userId) {
        exerciseService.deleteByUserId(userId);
    }


    @DeleteMapping("/user/{userId}/{date}")
    public void deleteExercisesByUserIdAndDate(
            @PathVariable Long userId,
            @PathVariable @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date) {
        exerciseService.deleteByUserIdAndDate(userId, date);
    }

    @DeleteMapping("/user/{userId}/{date}/{time}")
    public void deleteExercisesByUserIdAndDateAndTime(
            @PathVariable Long userId,
            @PathVariable @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date,
            @PathVariable @DateTimeFormat(iso = DateTimeFormat.ISO.TIME) LocalTime time) {
        exerciseService.deleteByUserIdAndDateAndTime(userId, date, time);
    }
}
